<template>
  <ele-page flex-table>
    <ComHeader :title="isUpdate ? `编辑销售单[${info.order_sn}]` : '新增销售单'" @back="goBack()" />
    <ele-bottom-bar :teleported="true">
      <el-space :size="20" :spacer="spacer">
        <div class="text-16px">本单应付：<span class="font-bold text-danger">{{ summary[1] }}</span></div>
        <div class="text-16px">实际应付：<span class="font-bold text-danger">{{ summary[3] }}</span></div>
      </el-space>
      <template #extra>
        <el-button type="primary" :loading="loading" @click="save">保存</el-button>
      </template>
    </ele-bottom-bar>
    <ele-card flex-table>
      <el-scrollbar>
        <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="form" :rules="rules" label-width="auto">
          <el-row>
            <el-col :span="20">
              <el-row :gutter="20">
                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="录单日期" prop="order_date">
                    <el-date-picker
                      v-model="form.order_date"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择录单日期"
                      class="w-full!"
                    />
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="税率" prop="tax_rate">
                    <el-input
                      v-model="form.tax_rate"
                      clearable
                      placeholder="请填写税率"
                      oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                      @blur="formatList()"
                    >
                      <template #suffix>
                        <el-text tag="b" type="danger">%</el-text>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="运费" prop="logistics_total">
                    <el-input
                      v-model="form.logistics_total"
                      clearable
                      placeholder="请填写运费"
                      oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                      @blur="setProductFee()"
                    >
                      <template #suffix>
                        <el-text tag="b" type="danger">元</el-text>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="整单优惠" prop="discount_total">
                    <el-input
                      v-model="form.discount_total"
                      clearable
                      placeholder="请整单优惠金额"
                      oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                      @input="value => inputDiscount(value)"
                    >
                      <template #suffix>
                        <el-text tag="b" type="danger">元</el-text>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="货主" prop="supplier_id">
                    <el-select
                      v-model="form.supplier_id"
                      :empty-values="['', null, undefined, 0]"
                      placeholder="请选择货主"
                      clearable
                    >
                      <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="仓库" prop="warehouse_id">
                    <el-select v-model="form.warehouse_id" :disabled="!form.supplier_id" placeholder="请选择仓库" clearable>
                      <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="客户" prop="customer_id">
                    <el-select v-model="form.customer_id" filterable placeholder="请选择客户" clearable @change="customerChange">
                      <el-option v-for="item in customerList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <!-- <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="供应商" prop="sup_sub_id">
                    <el-select v-model="form.sup_sub_id" :disabled="!form.supplier_id" filterable placeholder="请选择供应商" clearable>
                      <el-option v-for="item in subSupplierList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </el-col> -->

                <!-- <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="运费分摊" prop="share_type">
                    <el-radio-group v-model="form.share_type" @change="setProductFee()">
                      <el-radio-button label="不分摊" :value="0" />
                      <el-radio-button label="按金额" :value="1" :disabled="Math.sign(form.logistics_total) !== 1" />
                      <el-radio-button label="按数量" :value="2" :disabled="Math.sign(form.logistics_total) !== 1" />
                    </el-radio-group>
                  </el-form-item>
                </el-col> -->

                <el-col :md="6" />

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="收货人" prop="consignee">
                    <el-input v-model="form.consignee" clearable placeholder="请填写收货人" />
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="收货电话" prop="consignee_phone">
                    <el-input v-model="form.consignee_phone" clearable placeholder="请填写收货电话" />
                  </el-form-item>
                </el-col>

                <el-col :sm="12">
                  <el-form-item label="收货地址" prop="consignee_address">
                    <el-input v-model="form.consignee_address" type="textarea" autosize placeholder="请填写收货地址" />
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="物流公司" prop="logistics_name">
                    <el-input v-model="form.logistics_name" clearable placeholder="请填写物流公司" />
                  </el-form-item>
                </el-col>

                <el-col :md="6" :sm="12" :xs="24">
                  <el-form-item label="物流单号" prop="logistics_order_sn">
                    <el-input v-model="form.logistics_order_sn" clearable placeholder="请填写物流单号" />
                  </el-form-item>
                </el-col>

                <el-col :sm="12">
                  <el-form-item label="订单备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" autosize clearable placeholder="请填写备注" />
                  </el-form-item>
                </el-col>

                <!-- <el-divider border-style="dashed" content-position="left">
              <el-text type="info">商品信息</el-text>
            </el-divider> -->
              </el-row>
            </el-col>
            <el-col :span="4">
              <el-form-item label="附件" prop="enclosure">
                <FileUpload v-model="form.enclosure" :limit="8" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品信息" label-position="top" label-width="200px" prop="product">
                <template #label>
                  <span class="flex-inline items-center">
                    <div class="">商品信息</div>
                    <div class="ml-12px">
                      <el-button
                        type="primary"
                        icon="IconElPlus"
                        :disabled="!form.supplier_id"
                        plain
                        @click="showProduct = true"
                      >
                        新增商品
                      </el-button>
                    </div>
                  </span>
                </template>
                <el-table
                  ref="tableRef"
                  :data="form.product"
                  size="small"
                  border
                  style="width: 100%"
                  show-summary
                  class="form-table"
                  :summary-method="getSummaries"
                >
                  <el-table-column type="index" label="序" width="45" align="center" />
                  <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
                  <el-table-column prop="product_code" label="商品编码" align="center" />
                  <el-table-column prop="unit" label="主单位" align="center" width="100" />
                  <el-table-column
                    prop="sale_num"
                    label="商品数量"
                    align="center"
                    :width="Math.max(...form.product.map(v => v.multi_unit?.length), 1) * 110 + 60"
                  >
                    <template #default="{ row, $index }">
                      <div class="flex-a" :class="form.product.some(v => v.multi_unit?.length > 1) ? '' : 'justify-center'">
                        <el-space>
                          <el-form-item
                            v-for="(item, i) in row.multi_unit"
                            :key="i"
                            :label-width="0"
                            :prop="`product[${$index}].multi_unit[${i}].num`"
                            :required="row.multi_unit.every(v => !Number(v.num))"
                          >
                            <el-input
                              v-model="item.num"
                              size="small"
                              class="w-100px!"
                              placeholder="数量"
                              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                              @input="value => deHandleInput(value, $index, 'sale_num')"
                            >
                              <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
                            </el-input>
                          </el-form-item>
                        </el-space>
                        <div v-if="row.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
                          = {{ totalUnit(row.multi_unit) }}{{ row.unit }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="未税单价" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].price`" required>
                        <el-input
                          v-model="row.price"
                          size="small"
                          placeholder="未税单价"
                          input-style="text-align: center"
                          oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/,'$1')"
                          @input="value => deHandleInput(value, $index, 'price')"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="taxEnable" prop="tax_price" label="含税单价" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].tax_price`" required>
                        <el-input
                          v-model="row.tax_price"
                          size="small"
                          placeholder="含税单价"
                          input-style="text-align: center"
                          oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/,'$1')"
                          @input="value => deHandleInput(value, $index, 'tax_price')"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="total" label="未税金额" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].total`" required>
                        <el-input
                          v-model="row.total"
                          size="small"
                          placeholder="未税金额"
                          :disabled="row.sale_num <= 0"
                          input-style="text-align: center"
                          oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                          @input="value => deHandleInput(value, $index, 'total')"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="taxEnable" prop="tax_amount" label="税额" align="center" />
                  <el-table-column v-if="taxEnable" prop="tax_total" label="含税金额" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].tax_total`" required>
                        <el-input
                          v-model="row.tax_total"
                          size="small"
                          placeholder="含税金额"
                          :disabled="row.sale_num <= 0"
                          input-style="text-align: center"
                          oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                          @input="value => deHandleInput(value, $index, 'tax_total')"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="logistics_amount" label="运费分摊" align="center">
                    <template #default="{ row }">
                      <div>{{ row.logistics_amount }}</div>
                    </template>
                  </el-table-column> -->

                  <!-- <el-table-column prop="gift_num" label="赠送数量" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].gift_num`">
                        <el-input
                          v-model="row.gift_num"
                          size="small"
                          placeholder="赠送"
                          input-style="text-align: center"
                          oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                        >
                          <template #suffix><span class="text-#333!">{{ row.unit }}</span></template>
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="操作" width="75" align="center">
                    <template #default="{ $index }">
                      <el-link type="danger" underline="never" @click="removeProduct($index)">
                        <span
                          class="text-12px"
                        >删除</span>
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <SelectProduct
        v-model="showProduct"
        editPrice
        :decimal="4"
        :selecteds="form.product"
        :where="{ supplier_id: form.supplier_id }"
        @done="selectProduct"
      />
    </ele-card>
  </ele-page>
</template>

<script setup>
import { listBanWarehouse, listSupplier } from '@/api/common'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'
import FileUpload from '@/components/FileUpload/index.vue'
import { useDebounceFn } from '@vueuse/core'

defineOptions({ name: 'SaleEdit' })
const route = useRoute()
const router = useRouter()

const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()

const formRef = ref(null)
const tableRef = ref(null)

const { totalUnit, spacer } = utils

const orderId = ref(0)

/** 是否是修改 */
const isUpdate = computed(() => orderId.value > 0)

const taxEnable = computed(() => form.tax_rate > 0)

const loading = ref(false)

const warehouseList = ref([])

const showProduct = ref(false)

const [supplierList] = utils.useGetList(listSupplier)

const info = ref({})

const [customerList] = utils.useGetList('/customer/index', { is_all: 1 })

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  order_date: utils.formatDate(undefined, 'YYYY-MM-DD'),
  tax_rate: '', // 税率
  logistics_total: '', // 运费
  discount_total: '', // 整单优惠
  total: 0,
  tax_total: 0,
  sale_total: '',
  remark: '',
  supplier_id: undefined,
  warehouse_id: undefined,
  // sup_sub_id: '',
  customer_id: '',
  enclosure: '', // 附件
  share_type: 0, // 分摊方式：0不分摊 1 按金额 2 按数量
  logistics_order_sn: '',
  logistics_name: '',
  consignee: '',
  consignee_address: '',
  consignee_phone: '',
  product: [],
})

/** 表单验证规则 */
const rules = reactive({
  order_date: [
    {
      required: true,
      message: '请选择录单日期',
      trigger: 'change',
    },
  ],
  supplier_id: [
    {
      required: true,
      message: '请选择货主',
      trigger: 'change',
    },
  ],
  warehouse_id: [
    {
      required: true,
      message: '请选择仓库',
      trigger: 'change',
    },
  ],
  product: [
    {
      required: true,
      message: '请选择商品',
      type: 'array',
      trigger: 'change',
      min: 1,
    },
  ],
})

const summary = computed(() => {
  const data = form.product.reduce((acc, cur) => {
    acc[0] = utils.Big(acc[0]).plus(cur.sale_num).valueOf()
    acc[1] = utils.Big(acc[1]).plus(cur.tax_total).valueOf()
    return acc
  }, [0, 0])
  // 运费只做纪录，不参与运算 @2025.06.12
  data[2] = utils.Big(data[1]).plus(form.logistics_total).valueOf()
  data[3] = utils.Big(data[1]).minus(form.discount_total).valueOf()
  return data
})

function goBack(path) {
  if (!path)
    path = '/sale/index'
  removePageTab({ key: routeTabKey })
  router.push(path)
}

onMounted(() => {
  orderId.value = Number(route.params?.id)

  if (orderId.value) {
    getInfo()
  }
  else {
    setPageTabTitle('新增销售单')
  }
})

function getInfo() {
  utils.get('/sale/info', { id: orderId.value }).then((res) => {
    res.data.product.forEach((v) => {
      v.sale_num = v.num
    })
    info.value = res.data
    setPageTabTitle(`编辑销售单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
    assignFields({
      ...form,
      ...res.data,
      enclosure: utils.encodeFiles(res.data.enclosure),
    })
  })
}

// const subSupplierList = ref([]) // 子供应商

// function getSubSupplierList(supplier_id) {
//   if (!supplier_id) {
//     subSupplierList.value = []
//     form.sup_sub_id = undefined
//   }
//   utils.get('supplierSub/index', { supplier_id, is_all: 1 }).then((res) => {
//     subSupplierList.value = res.data
//     if (form.sup_sub_id && !subSupplierList.value.some(v => v.id === form.sup_sub_id)) {
//       form.sup_sub_id = ''
//     }
//   })
// }

watch(() => form.supplier_id, async (newVal, oldVal) => {
  if (oldVal) {
    form.product = []
  }
  // getSubSupplierList(newVal) // 子供应商 @2025-08-07
  if (newVal) {
    const res = await listBanWarehouse(newVal)
    warehouseList.value = res.data
  }
  else {
    warehouseList.value = []
  }
  if (form.warehouse_id && !warehouseList.value.some(v => v.id === form.warehouse_id)) {
    form.warehouse_id = ''
  }
}, {
  immediate: true,
})

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    const formData = utils.cloneDeep(form)

    if (isUpdate.value) {
      formData.id = orderId.value
    }

    formData.enclosure = utils.decodeFiles(formData.enclosure)
    formData.product = formData.product.map((d) => {
      // d.id = undefined
      // d.logistics_amount = d.logistics_amount || 0
      // d.sale_num = undefined
      d.num = utils.Big(d.sale_num).plus(d.gift_num).valueOf()

      return {
        product_id: d.product_id,
        price: d.price,
        tax_price: d.tax_price,
        total: d.total,
        tax_total: d.tax_total,
        num: d.num,
        tax_amount: d.tax_amount,
        multi_unit: d.multi_unit,
      }
    })

    const sums = formData.product.reduce((acc, cur) => {
      acc.tax_amount = utils.Big(acc.tax_amount).plus(cur.tax_amount).valueOf()
      acc.tax_total = utils.Big(acc.tax_total).plus(cur.tax_total).valueOf()
      return acc
    }, { tax_amount: 0, tax_total: 0 })
    formData.tax_total = sums.tax_total
    formData.tax_amount = sums.tax_amount
    formData.total = utils.Big(sums.tax_total).minus(sums.tax_amount).valueOf()
    formData.sale_total = utils.Big(sums.tax_total).minus(formData.discount_total).valueOf()
    formData.share_status = formData.share_type > 0 ? 1 : 0

    // START : 采购单有的功能，不知道采购单后期会不会扩展，先实现再隐藏，有期有需要就启用
    formData.discount_type = 1
    formData.discount_val = formData.discount_total
    formData.share_type = undefined
    formData.share_status = undefined
    formData.logistics_total = undefined
    // END : 采购单有的功能，不知道采购单后期会不会扩展，先实现再隐藏，有期有需要就启用

    utils.post('/sale/edit', formData)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          if (typeof res.data?.id === 'number' && res.data.id > 0) {
            goBack(`/sale/index/info/${res.data.id}`)
          }
          else {
            goBack()
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

function selectProduct(data, row) {
  if (data.length) {
    data.forEach((v) => {
      // v.multi_unit = v.unit_list.map(d => ({ ...d, num: '' }))
      const sale_num = utils.totalUnit(v.multi_unit)
      v.multi_unit = sale_num > 0 ? v.multi_unit : v.unit_list.map(d => ({ ...d, num: '' }))
      v.sale_num = sale_num || ''
    })
    form.product.push(...data)
  }
  else if (row) {
    const index = form.product.findIndex(v => v.product_id === row.product_id)
    if (index === -1) {
      form.product.push(row)
    }
    else {
      form.product[index] = row
    }
  }

  const keys = data.length ? data.map(v => v.product_id) : row ? [row.product_id] : []
  formatList(keys)

  setTimeout(() => {
    tableRef.value.doLayout()
  }, 200)
}

async function customerChange(id) {
  if (!id) {
    return
  }
  const data = customerList.value.find(v => v.id === id)
  if (!data) {
    return
  }
  data.consignee = data.contact
  data.consignee_phone = data.phone
  data.consignee_address = data.address
  if (!data.consignee && !data.consignee_phone && !data.consignee_address) {
    return
  }
  if (form.consignee || form.consignee_address || form.consignee_phone) {
    const [cancel] = await utils.awaitTo(utils.confirm(`是否使用${data.name}仓库的默认收货地址`, '系统提示'))
    if (cancel)
      return
  }
  if (data.consignee)
    form.consignee = data.consignee
  if (data.consignee_phone)
    form.consignee_phone = data.consignee_phone
  if (data.consignee_address)
    form.consignee_address = data.consignee_address
}

function removeProduct(index) {
  form.product.splice(index, 1)
  formatList()
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['sale_num', 'total', 'tax_amount', 'tax_total', 'gift_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => utils.Big(acc).plus(cur[column.property]).valueOf(), 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}

function ufunc(rate) {
  rate = rate > 0 ? utils.Big(rate).div(100).toNumber() : 0
  const rateFill = utils.Big(rate).plus(1).toNumber()

  //  含税单价 = 单价 * (1 + 税率)
  const getTaxPrice = p => utils.Big(p).times(rateFill).round(4).toNumber() || ''

  //  税额 = 单价 * 数量 * 税率
  const getTaxAmount = (p, n) => rate ? utils.Big(p).times(n).times(rate).round(2).toNumber() : 0

  // 未税金额 = 单价 * 数量
  const getTotal = (p, n) => utils.Big(p).times(n).round(4).toNumber() || ''

  // 未税金额 = 含税金额 - 税额
  const getTotalByMinus = (p1, p2) => utils.Big(p1).minus(p2).toNumber() || ''

  // 含税金额 = 单价 * 数量 * (1 + 税率)
  const getTaxTotal = (p, n) => utils.Big(p).times(n).times(rateFill).round(2).toNumber() || ''

  //  单价 =  含税单价 / (1 + 税率)
  const getPrice = p => utils.Big(p).div(rateFill).round(4).toNumber() || ''

  return { getTaxPrice, getTaxAmount, getTotal, getTotalByMinus, getTaxTotal, getPrice, rate }
}

function formatList(keys = []) {
  const { getTaxPrice, getTaxAmount, getTotalByMinus, getTaxTotal } = ufunc(form.tax_rate)
  form.product.forEach((v) => {
    if (keys?.length && !keys.includes(v.product_id)) {
      return
    }
    v.tax_price = getTaxPrice(v.price)
    v.tax_amount = getTaxAmount(v.price, v.sale_num)
    v.tax_total = getTaxTotal(v.price, v.sale_num)
    v.total = getTotalByMinus(v.tax_total, v.tax_amount)
  })
  inputDiscount(form.discount_total)
  setProductFee()
}

function handleInput(value, index, type = '') {
  /**
   * price:未税单价; tax_price:含税单价; total:未税金额; tax_total:含税金额; tax_amount:税额;
   * 含税金额公式 (示例： 单价=100.58;数量=11.22;税率:13%)
   * 含税单价 = 单价 * (1 + 税率)
   * 未税金额 = 单价 * 数量 = 100.58*11.22 = 1128.5076 ≈ 1128.51
   * 含税金额 = 单价 * 数量 * (1 + 税率) = 100.58*11.22*1.13 = 1275.213588 ≈ 1275.21
   * 税额 = 单价 * 数量 * 税率 = 100.58*11.22*0.13 = 1128.5076 ≈ 146.705988 ≈ 146.71
   * 未税金额尾差调整 = 含税金额 - 税额 =  1275.21 - 146.71 = 1128.50
   */
  // const rate = form.tax_rate > 0 ? utils.Big(form.tax_rate).div(100).toNumber() : 0
  // const rateFill = utils.Big(rate).plus(1).toNumber()

  // //  含税单价 = 单价 * (1 + 税率)
  // const getTaxPrice = p => utils.Big(p).times(rateFill).round(4).toNumber() || ''

  // //  税额 = 单价 * 数量 * 税率
  // const getTaxAmount = (p, n) => rate ? utils.Big(p).times(n).times(rate).round(2).toNumber() : 0

  // // 未税金额 = 单价 * 数量
  // const getTotal = (p, n) => utils.Big(p).times(n).round(4).toNumber() || ''

  // // 未税金额 = 单价 * 数量
  // const getTotalByMinus = (p1, p2) => utils.Big(p1).minus(p2).toNumber() || ''

  // // 含税金额 = 单价 * 数量 * (1 + 税率)
  // const getTaxTotal = (p, n) => utils.Big(p).times(n).times(rateFill).round(2).toNumber() || ''

  // //  单价 =  含税单价 / (1 + 税率)
  // const getPrice = p => utils.Big(p).div(rateFill).round(4).toNumber() || ''

  const { getTaxPrice, getTaxAmount, getTotalByMinus, getTaxTotal, getPrice, rate } = ufunc(form.tax_rate)

  const row = utils.cloneDeep(form.product[index])

  if (type === 'sale_num') {
    row.sale_num = totalUnit(row.multi_unit)
    row.tax_price = getTaxPrice(row.price)
    row.tax_amount = getTaxAmount(row.price, row.sale_num)
    row.tax_total = getTaxTotal(row.price, row.sale_num)
    row.total = getTotalByMinus(row.tax_total, row.tax_amount)
  }
  else if (type === 'price') {
    row[type] = value
    row.tax_price = getTaxPrice(value)
    row.tax_amount = getTaxAmount(value, row.sale_num)
    row.tax_total = getTaxTotal(value, row.sale_num)
    row.total = getTotalByMinus(row.tax_total, row.tax_amount)
  }
  else if (type === 'tax_price') {
    row[type] = value
    row.price = getPrice(value)
    row.tax_amount = getTaxAmount(row.price, row.sale_num)
    row.tax_total = getTaxTotal(row.price, row.sale_num)
    row.total = getTotalByMinus(row.tax_total, row.tax_amount)
  }
  else if (type === 'total') {
    row.price = utils.Big(value).div(row.sale_num).round(4).toNumber() || ''
    row.tax_price = getTaxPrice(row.price)
    row.tax_amount = getTaxAmount(row.price, row.sale_num)
    row.tax_total = getTaxTotal(row.price, row.sale_num)
    const totalValue = getTotalByMinus(row.tax_total, row.tax_amount)
    if (utils.Big(row.sale_num).eq(0) || utils.Big(value).eq(totalValue)) {
      row.total = value
    }
    else {
      row.total = totalValue
    }
  }
  else if (type === 'tax_total') {
    row[type] = value
    row.tax_amount = utils.Big(value).times(rate).round(2).toNumber() || ''
    row.total = getTotalByMinus(value, row.tax_amount)
    row.tax_price = utils.Big(value).div(row.sale_num).round(4).toNumber()
    row.price = getPrice(row.tax_price)
  }

  let logistics = false
  if (
    (form.share_type === 1 && form.product[index].tax_total !== row.tax_total)
    || (form.share_type === 2 && form.product[index].sale_num !== row.sale_num)
  ) {
    logistics = true
  }

  form.product[index] = row

  if (logistics)
    setProductFee()

  // formRef.value.validate()
}

function inputDiscount(value) {
  if (utils.Big(value).gt(summary.value[1])) {
    form.discount_total = summary.value[1]
  }
}

/**
 * 分摊运费
 */
function setProductFee() {
  if (form.share_type === 0) {
    form.product.forEach((v) => {
      v.logistics_amount = 0
    })
  }
  // 按金额分摊：每列分摊运费= (列含税金额 / 含税总额) * 运费
  else if (form.share_type === 1) {
    form.product.forEach((v) => {
      const per = utils.Big(v.tax_total).div(summary.value[1]).round(4).valueOf()
      v.logistics_amount = utils.Big(form.logistics_total).times(per).round(4).valueOf()
    })
  }
  // 按数量分摊：每列费用分摊 = 运费/总数量*列数量
  else if (form.share_type === 2) {
    const logistics = utils.Big(form.logistics_total).div(summary.value[0]).round(4).valueOf()
    form.product.forEach((v) => {
      v.logistics_amount = utils.Big(logistics).times(v.sale_num).round(4).valueOf()
    })
  }
}

const deHandleInput = useDebounceFn(handleInput, 100)
</script>

<style lang="scss" scoped></style>
